<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    /**
     * Overriding php options
     */
    protected function _initPhp()
    {
        // disabling register globals
        if (ini_get('register_globals') && ini_set('register_globals',0)===false) trigger_error('Could not disable register_globals option',E_USER_NOTICE);
        
        // disabling magic_quotes_gpc
        if (get_magic_quotes_gpc())
        {
            $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
            while (list($key, $val) = each($process)) {
                foreach ($val as $k => $v) {
                    unset($process[$key][$k]);
                    if (is_array($v)) {
                        $process[$key][stripslashes($k)] = $v;
                        $process[] = &$process[$key][stripslashes($k)];
                    } else {
                        $process[$key][stripslashes($k)] = stripslashes($v);
                    }
                }
            }
            unset($process);
        }
    }
    
     /**
     * Initializing configuration
     * Saving configuration object to registry
     *
     * @return object
     */
    protected function _initConf()
    {
        $config = new Zend_Config_Ini(APPLICATION_PATH.'/configs/config.ini', 'main');
        
        Zend_Registry::set('config',$config);
        
        return $config;
    }
    
    /**
     * Initializing front controller;
     * Saving front controller object to registry
     *
     * @return object
     */
    protected function _initController()
    {
        $this->bootstrap('frontController');
        $front = Zend_Controller_Front::getInstance();
        
        Zend_Registry::set('frontController',$front);
        
        return $front;
    }
    
    /**
     * Saving view object to registry
     *
     * @return unknown
     */
    protected function _initViewObj()
    {
        $this->bootstrap('view');
        $view=$this->getResource('view');
        
        Zend_Registry::set('view',$view);
        
        return $view;
    }
    
    /**
     * Initializing layout
     * Saving layout object to registry
     *
     * @return object
     */
    protected function _initLayoutObj()
    {
        $this->bootstrap('layout');
        $layout=$this->getResource('layout');
        
        Zend_Registry::set('layout',$layout);
        
        return $layout;
    }
    
    /**
     * Initializing jQuery
     *
     */
    protected function _initJquery()
    {
        $view=Zend_Registry::get('view');
        
        $view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");

        $view->jQuery()->setLocalPath(Zend_Registry::get('config')->site->directory.'js/jquery/jquery-1.3.2.min.js');
        $view->jQuery()->setUiLocalPath(Zend_Registry::get('config')->site->directory.'js/jquery/jquery-ui-1.7.2.min.js');
        $view->jQuery()->addStylesheet(Zend_Registry::get('config')->site->directory.'css/jquery/vader/jquery-ui-1.7.2.css');
        
        $viewRenderer = new Zend_Controller_Action_Helper_ViewRenderer();
        $viewRenderer->setView($view);
        Zend_Controller_Action_HelperBroker::addHelper($viewRenderer);
    }
    
    /**
     * Initializing placeholders
     *
     */
    protected function _initPlaceholders()
    {
        $view=Zend_Registry::get('view');
        
        $view->placeholder('authform')
             ->setPrefix('<div id="auth-form"><div class="auth-form-item">')
             ->setSeparator('</div><div class="auth-form-item">')
             ->setPostfix('</div></div>');
             
        $view->placeholder('searchbar')
             ->setPrefix('<div id="sidebar"><div class="sidebar-item"><div class="sidebar-content">')
             ->setSeparator('')
             ->setPostfix('</div></div></div>');
             
        $view->placeholder('sidebar')
             ->setPrefix('<div id="sidebar"><div class="sidebar-item"><div class="sidebar-content">')
             ->setSeparator('</div></div><div class="sidebar-item"><div class="sidebar-content">')
             ->setPostfix('</div></div></div>');
             
        $view->placeholder('adminpanel')
             ->setPrefix('<div id="admin-panel"><div class="admin-panel-item">')
             ->setSeparator('</div><div class="admin-panel-item">')
             ->setPostfix('</div></div>');
    }
    
    /**
     * Loading styles and scripts
     *
     */
    protected function _initHeads()
    {
        $view=Zend_Registry::get('view');
        
        $view->headTitle()->setSeparator(' : ');
        $view->headLink()->appendStylesheet($view->baseUrl('css/style.css'));
        $view->headScript()->appendFile($view->baseUrl('js/scripts.js'));
        
        $view->jQuery()->enable();
    }
    
    /**
     * Initializing helpers
     *
     */
    protected function _initHelpers()
    {
        $view=Zend_Registry::get('view');
        
        $view->addHelperPath(APPLICATION_PATH.'/views/helpers/', 'Helper');
    }
    
    /**
     * Initializing db
     * Saving db object to registry
     *
     * @return object
     */
    protected function _initDbObj()
    {
        $this->bootstrap('db');
        $db = $this->getResource('db');
        
        Zend_Db_Table_Abstract::setDefaultAdapter($db);
        
        $db->query('SET NAMES utf8');
        
        Zend_Registry::set('db', $db);

        return $db;
    }
    
    protected function _initSession()
    {
        $config = array(
            'name'           => 'session',
            'primary'        => 'id',
            'modifiedColumn' => 'modified',
            'dataColumn'     => 'data',
            'lifetimeColumn' => 'lifetime'
        );
        
        Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
        
        Zend_Session::start();
    }
    
    /**
     * Initializing cache
     * Saving cache object to registry
     */
    protected function _initCache()
    {
        $frontendOptions = array(
         'lifetime' => Application_Model_Cache::CACHE_LIFETIME, 
         'automatic_serialization' => true
        );

        $backendOptions = array(
          'cache_dir' => ROOT_DIR.'/'.Application_Model_Cache::CACHE_DIR
        );

        $cache = Zend_Cache::factory('Core',
                                   'File',
                                   $frontendOptions,
                                   $backendOptions);
                                   
        Zend_Registry::set('cache',$cache);
    }
    
    /**
     * Initializing serializer
     * Saving serializer object to registry
     *
     * @return object
     */
    protected function _initSerializer()
    {
        $serializer = Zend_Serializer::factory('PhpSerialize');
        
        Zend_Registry::set('serializer',$serializer);
        
        return $serializer;
    }
    
    /**
     * Initializing locale
     * Saving locale object to registry
     *
     * @return object
     */
    protected function _initLocale()
    {
        $language=null;
        
        if (!empty($_SERVER['REQUEST_URI']))
        {
            $params=explode('/',trim($_SERVER['REQUEST_URI'],'/'));
            
            if (!empty($params) && Application_Model_Locale::isValidLocale($params[0]))
                $language=$params[0];
        }
            
        $locale=new Application_Model_Locale($language);
        
        Zend_Registry::set('language',$locale);

        Application_Model_Locale::setTranslation($language);
    }
    
    /**
     * Initializing routes
     * Saving router object to registry
     *
     * @return object
     */
    protected function _initRouter() 
    {
        $front=Zend_Registry::get('frontController');

        $router = $front->getRouter();

        $routesObj=new Zend_Config_Ini(APPLICATION_PATH.'/configs/routes.ini', 'default');
        $routes=$routesObj->routes->toArray();
        
        foreach ($routes as $id=>$route)
        {
            $route_parts=explode('/', $route);
            $controller=!empty($route_parts[0]) ? $route_parts[0] : 'index';
            $action=!empty($route_parts[1]) ? $route_parts[1] : 'index';
            
            $router->addRoute('default'.$controller.$action.$id, 
                                new Zend_Controller_Router_Route($route,array(
                                    'controller' => $controller,
                                    'action' => $action,
                                    'module' => 'default'
                                ))
                            ); 
                            
            $router->addRoute('default'.$controller.$action.$id.'language', 
                                new Zend_Controller_Router_Route(':language/'.$route,array(
                                    'controller' => $controller,
                                    'action' => $action,
                                    'module' => 'default'
                                ))
                            );
        }
        
        Zend_Registry::set('router',$router);
        
        return $router;
    }
    
    /**
     * Seting resources
     * Saving resources array to registry
     * Saving resources object to registry
     *
     */
    protected function _initResources()
    {
        $resources=array(
            Application_Model_UserResources::getFrontResource(), // front page resource
            Application_Model_UserResources::getUserResource(),  // user resource
            Application_Model_UserResources::getNodeResource(),   // node resource
            Application_Model_UserResources::getFileResource(),   // file resource
            Application_Model_UserResources::getLogResource(),   // log resource
            Application_Model_UserResources::getCacheResource()   // cache resource
        );
        
        Zend_Registry::set('resources', $resources);
        
        $resourcesObj=new Application_Model_UserResources();
        Zend_Registry::set('resourcesObj', $resourcesObj);
    }
    
    /**
     * Seting active resource to controller name
     *
     */
    protected function _initResource()
    {
        Zend_Registry::set('resource', Application_Model_UserResources::getDefaultResource());
    }
    
    /**
     * Initializing user
     * Saving user object to registry
     *
     * @return object
     */
    protected function _initUser()
    {
        $auth=new Application_Model_UserAuth();
        $auth_login=$auth->getAuthUserLogin();
        
        if (!empty($auth_login))
        {
            $userDb=new Application_Model_UserDb();
            
            $user=$userDb->fetchUserByLogin($auth_login);
            
            $user->blockNonActiveUser();
        } else 
        {
            $user=new Application_Model_User();
        }
        
        Zend_Registry::set('user',$user);
        
        return $user;
    }
    
    /**
     * Initializing access permissions
     * Saving access object to registry
     *
     * @return object
     */
    protected function _initAccess()
    {
        $access=new Application_Model_UserPerms();
        
        Zend_Registry::set('access',$access);
        
        //seting access permissions for user resource
        $access->allow(Application_Model_UserRoles::getUserRole(),Application_Model_User::RESOURCE_NAME,Application_Model_UserPerms::VIEW_PERM); // only logged in users can view other users profile
        
        if (Zend_Registry::get('config')->user->register)
        {
            $access->allow(Application_Model_UserRoles::getDefaultRole(),Application_Model_User::RESOURCE_NAME,Application_Model_UserPerms::POST_PERM); // allow registration for everybody
        }
        
        //seting access permissions for node resource
        Zend_Registry::get('access')->allow(Application_Model_UserRoles::getDefaultRole(),Application_Model_Node::RESOURCE_NAME,Application_Model_UserPerms::VIEW_PERM); // everybody can view nodes
        
        //seting access permissions for front page
        Zend_Registry::get('access')->allow(Application_Model_UserRoles::getDefaultRole(),Application_Model_UserResources::getFrontResource(),Application_Model_UserPerms::VIEW_PERM); // everybody can access front page
        
        //seting access permissions for log management
        Zend_Registry::get('access')->allow(Application_Model_UserRoles::getAdminRole(),Application_Model_UserResources::getLogResource(),Application_Model_UserPerms::VIEW_PERM); // only admin can access logs
        
        return $access;
    }
    
    /**
     * Initializing main navigation menu
     *
     */
    protected function _initNavigation()
    {
        $view=Zend_Registry::get('view');
        
        $nav_conf=new Zend_Config_Ini(APPLICATION_PATH.'/configs/navigation.ini', 'navigation');
        $navigation = new Zend_Navigation($nav_conf);
        
        $iterator = new RecursiveIteratorIterator($navigation, RecursiveIteratorIterator::SELF_FIRST);
        
        foreach ($iterator as $nav)
        {
            $nav->label=Zend_Registry::get('locale')->_($nav->label);
            
            if ($nav->uri==trim($_SERVER['REQUEST_URI'],'/'))
            {
                $nav->active=true;
            }
            
            $nav->uri=Zend_Registry::get('view')->fixUrl($nav->uri);
        }
        
        $view->navigation($navigation);
        
        Zend_Registry::set('navigation',$navigation);
        
        if (Zend_Registry::get('config')->site->drop_down_menu)
        {
            $this->view->jMenu(); 
        }
    }

    /**
     * Initializing paginator
     *
     */
    protected function _initPagination()
    {
        Zend_Paginator::setDefaultScrollingStyle('Sliding');
        Zend_View_Helper_PaginationControl::setDefaultViewPartial(
            'pagination.phtml'
        );
    }
    
    /**
     * Logging access
     */
    protected function _initLog()
    {
        $ip=getenv('REMOTE_ADDR');
        $pip=getenv('HTTP_X_FORWARDED_FOR');
        if ($pip)
        {
            $ip=$pip;
        } elseif (!$ip)
        {
            $ip='Hidden';
        }
        
        $ua=isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Unknown';
        $referer=!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'none';
        $url=!empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
        
        $log=array(
            'ip' => $ip,
            'ua' => $ua,
            'referer' => $referer,
            'url' => $url,
            'tstamp' => time()
            );
            
        $logObj=new Application_Model_Log($log);
            
        $log_tbl=new Application_Model_LogDb();
        $log_tbl->save($logObj);
    }
}

